import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import 'package:cave_flutter/network/whl_api.dart';

class Cave_homeLogic extends GetxController {
  TextEditingController editingController = TextEditingController();

  List<dynamic> officialCategory = [];
  List<dynamic> officialCategoryEven = [];
  List<dynamic> officialCategoryOdd = [];
  int caveNum = 0;
  int caveUserNum = 0;
  String officialCategoryActive = '';
  List<dynamic> caveTop5List = [];
  List<dynamic> officialCaves = [];
  List<dynamic> personCaves = [];
  List<dynamic> randomAvatars = [];

  @override
  void onInit() {
    super.onInit();
    getOfficialCategory();
    getCaveTop5();
    getPersonalCategory();
    // update();
  }

  toDetailPage(int id) {
    Get.toNamed(Routes.caveDetailPage, arguments: {'id': id});
  }

  toJoinPage(int id) {
    Get.toNamed(Routes.caveJoinPage, arguments: {'id': id});
  }

  getOfficialCategory() async {
    ResponseData responseData = await WhlApi.getCaveCategory.get({'type': 1});
    if (responseData.isSuccess()) {
      officialCategory = responseData.data;
      officialCategoryEven = responseData.data
          .asMap()
          .entries
          .where((element) => element.key % 2 == 1)
          .map((entry) => entry.value)
          .toList();
      officialCategoryOdd = responseData.data
          .asMap()
          .entries
          .where((element) => element.key % 2 == 0)
          .map((entry) => entry.value)
          .toList();

      if (responseData.data.isNotEmpty) {
        officialCategoryActive = responseData.data[0]['id'];
        getOfficialCaveList(officialCategoryActive);
      }
      update();
    }
  }

  getOfficialCaveList(String categories) async {
    ResponseData responseData = await WhlApi.searchCave.post({
      'caveCategories': categories,
    });

    if (responseData.isSuccess()) {
      officialCaves = responseData.data['records'];
      update();
      // update();
    }
  }

  getCaveTop5() async {
    ResponseData responseData = await WhlApi.getHotCave.get({});
    if (responseData.isSuccess()) {
      caveNum = responseData.data['caveNum'];
      caveUserNum = responseData.data['caveUserNum'];
      caveTop5List = responseData.data['caveInfo'];
      randomAvatars = responseData.data['randomAvatars'];
      update();
    }
  }

  getPersonalCategory() async {
    ResponseData responseData = await WhlApi.getPersonalCategory.get({});
    if (responseData.isSuccess()) {
      personCaves = responseData.data;
      update();
    }
  }
}
